package com.yeskery.transfer.data;

import com.yeskery.transfer.config.DataBaseProperties;
import com.yeskery.transfer.core.SproutException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 连接的工具类
 * @author shuangjiang.du
 * @date 2018-12-13 20:25
 * @version 1.0
 */
public class ConnectionKit {

	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			throw new SproutException("Database driver does not exist.", e);
		}
	}

	/**
	 * 获取数据库连接
	 * @param transferProperties 数据库配置信息
	 * @return 数据库连接
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public Connection getConnection(DataBaseProperties.TransferProperties transferProperties)
			throws ClassNotFoundException, SQLException {
		return DriverManager.getConnection(transferProperties.getURL(),
				transferProperties.getUsername(), transferProperties.getPassword());
	}

	/**
	 * 判断连接是否有效
	 * @param transferProperties 数据库配置信息
	 * @return <code>true</code> for valid, else not.
	 */
	public boolean testConnection(DataBaseProperties.TransferProperties transferProperties) {
		try (Connection connection = getConnection(transferProperties)){
			return connection != null;
		} catch (Exception e) {
			System.err.println(e.getMessage());
			return false;
		}
	}
}
